import { ref, Ref } from 'vue'

/**
 * 节流hook
 * @param fn 需要节流的函数
 * @param delay 延迟时间，默认300ms
 * @returns 节流后的函数
 */
export function useThrottle<T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 300
): T {
  let lastTime = 0
  
  return ((...args: any[]) => {
    const now = Date.now()
    if (now - lastTime >= delay) {
      fn(...args)
      lastTime = now
    }
  }) as T
}

/**
 * 节流状态hook
 * @param delay 延迟时间，默认300ms
 * @returns 节流状态和节流函数
 */
export function useThrottleState<T>(initialValue: T, delay: number = 300) {
  const state = ref<T>(initialValue) as Ref<T>
  let lastTime = 0
  
  const setState = (value: T) => {
    const now = Date.now()
    if (now - lastTime >= delay) {
      state.value = value
      lastTime = now
    }
  }
  
  return {
    state,
    setState
  }
}

/**
 * 带立即执行的节流hook
 * @param fn 需要节流的函数
 * @param delay 延迟时间，默认300ms
 * @param immediate 是否立即执行，默认true
 * @returns 节流后的函数
 */
export function useThrottleImmediate<T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 300,
  immediate: boolean = true
): T {
  let lastTime = 0
  let isFirst = immediate
  
  return ((...args: any[]) => {
    const now = Date.now()
    if (isFirst || now - lastTime >= delay) {
      fn(...args)
      lastTime = now
      isFirst = false
    }
  }) as T
} 